package com.seveneight.baijiesteward.http;

import android.content.Context;
import android.os.Handler;

import com.afollestad.materialdialogs.MaterialDialog;
import com.seveneight.baijiesteward.R;
import com.seveneight.baijiesteward.base.BaseActivity;
import com.seveneight.baijiesteward.bean.BaseEntity;
import com.seveneight.baijiesteward.utils.LogUtil;
import com.seveneight.baijiesteward.utils.ToastUtil;

import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * 无提示框
 */

public abstract class XObserver<T> implements Observer<BaseEntity<T>> {
    protected Context mContext;
    protected String message;


    public XObserver() {
    }
    public XObserver(Context mContext) {
        this.mContext=mContext;
    }

    @Override
    public void onSubscribe(Disposable d) {
    }

    @Override
    public void onNext(BaseEntity<T> tBaseEntity) {
        if (tBaseEntity.isSuccess()) {
            try {
                LogUtil.d("success:" + tBaseEntity.toString());
                onSuccees(tBaseEntity);
            }   catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                LogUtil.d("error:" + tBaseEntity.toString());
                onCodeError(tBaseEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            int code = httpException.code();
            if (code == 500 || code == 404) {
                ToastUtil.show(mContext, "连接失败，请稍后再试");
            } else if (code == 504) {
                ToastUtil.show(mContext, "请求失败，请检查网络连接");
            }
        } else if (e instanceof ConnectException) {
            ToastUtil.show(mContext, "网络断开,请打开网络");
        } else if (e instanceof SocketTimeoutException) {
            ToastUtil.show(mContext, "网络连接超时");
        } else if (e instanceof NoRouteToHostException) {
            ToastUtil.show(mContext, "无法连接到服务器");
        }
    }

    @Override
    public void onComplete() {

    }

    /**
     * 返回成功
     *
     * @param t
     * @throws Exception
     */
    protected abstract void onSuccees(BaseEntity<T> t) throws Exception;

    /**
     * 返回成功了,但是code错误
     *
     * @param t
     * @throws Exception
     */
    protected void onCodeError(final BaseEntity<T> t) throws Exception {
        ToastUtil.show(mContext, t.getRespMsg());
    }

    /**
     * 返回失败
     *
     * @param e
     * @param isNetWorkError 是否是网络错误
     * @throws Exception
     */
    protected abstract void onFailure(Throwable e, boolean isNetWorkError) throws Exception;
}
